package com.hsnn.medstgmini.base.std.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.impl.BaseHibernateDAO;
import com.hsnn.medstgmini.base.std.dao.StdHealthbureauDao;
import com.hsnn.medstgmini.base.std.model.StdHealthbureau;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.sys.model.RegHealthbureau;

@Repository
public class StdHealthbureauDaoImpl extends BaseHibernateDAO implements
		StdHealthbureauDao {

	@Autowired
	private HibernateSqlUtil dao;
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	/**
	 * @category 获取存在的卫生局
	 * @author 韩守松
	 * @date 2015年11月3日
	 * @param @param regHealthbureau
	 * @param @return
	 */
	@SuppressWarnings("unchecked")
	public StdHealthbureau getExistHeaBur(RegHealthbureau regHealthbureau) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(StdHealthbureau.class);
		if (regHealthbureau != null) {
			criteria.add(Restrictions.eq("heaBurName",
					regHealthbureau.getHeaBurName()));
			List<StdHealthbureau> list = criteria.list();
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		}
		return null;
	}

	/**
	 * @category 保存卫生局信息
	 * @author 韩守松
	 * @date 2015年11月3日
	 * @param @param stdHealthbureau
	 * @param @param opType
	 */
	public void saveHeaBurInfo(StdHealthbureau stdHealthbureau, int opType) {
		Session session = getSession();
		if (stdHealthbureau != null) {
			stdHealthbureau.setUpdTime(new Date());
			if (opType == 1
					&& StringUtils.isNotBlank(stdHealthbureau.getHeaBurId())) {
				StdHealthbureau oldStdHealthbureau = getHeaBurInfoById(stdHealthbureau
						.getHeaBurId());
				session.evict(oldStdHealthbureau);
				StringBuffer sql = new StringBuffer()
						.append("	update std_healthbureau a set 	")
						.append("	a.hea_bur_code = ?,a.hea_bur_name = ?,a.bur_spel_code = ?, ")
						.append("	a.area_id = ?,a.hea_bur_type = ?,a.org_code = ?,a.hosp_address = ?,a.hosp_phone = ?,	")
						.append("	a.staff_num = ?,a.profile = ?,a.contact_name = ?,a.contact_idnum = ?, a.contact_pos = ?, ")
						.append("   a.contact_telephone = ?,a.contact_handphone = ?, a.contact_email = ?,a.contact_qq = ?, ")
						.append(" 	a.status = ?,a.upd_time = ?,a.upd_user = ? ")
						.append("   where a.hea_bur_id = ? ");
				Query query = session.createSQLQuery(sql.toString());

				query.setParameter(0, stdHealthbureau.getHeaBurCode());
				query.setParameter(1, stdHealthbureau.getHeaBurName());
				query.setParameter(2, stdHealthbureau.getBurSpelCode());
				query.setParameter(3, stdHealthbureau.getArea().getAreaid());
				query.setParameter(4, stdHealthbureau.getHeaBurType());
				query.setParameter(5, stdHealthbureau.getOrgCode());
				query.setParameter(6, stdHealthbureau.getHospAddress());
				query.setParameter(7, stdHealthbureau.getHospPhone());
				query.setParameter(8, stdHealthbureau.getStaffNum());
				query.setParameter(9, stdHealthbureau.getProfile());
				query.setParameter(10, stdHealthbureau.getContactName());
				query.setParameter(11, stdHealthbureau.getContactIdnum());
				query.setParameter(12, stdHealthbureau.getContactPos());
				query.setParameter(13, stdHealthbureau.getContactTelephone());
				query.setParameter(14, stdHealthbureau.getContactHandphone());
				query.setParameter(15, stdHealthbureau.getContactEmail());
				query.setParameter(16, stdHealthbureau.getContactQQ());
				query.setParameter(17, stdHealthbureau.getStatus());
				query.setParameter(18, stdHealthbureau.getUpdTime());
				query.setParameter(19, stdHealthbureau.getUpdUser());

				query.setParameter(20, stdHealthbureau.getHeaBurId());
				query.executeUpdate();
				session.flush();
				writeLog(stdHealthbureau.getHeaBurId());
			} else {
				if (StringUtils.isBlank(stdHealthbureau.getHeaBurId())) {
					stdHealthbureau.setHeaBurId(UUID.randomUUID().toString());
				}
				StringBuffer sqlAdd = new StringBuffer()
						.append(" insert into std_healthbureau(hea_bur_id,hea_bur_code,hea_bur_name,bur_spel_code,area_id,hea_bur_type,org_code,hosp_address,hosp_phone,staff_num,profile,contact_name,contact_idnum,contact_pos,contact_telephone,contact_handphone,contact_email,contact_qq,status,upd_time,upd_user) ")
						.append(" values(:hea_bur_id,:hea_bur_code,:hea_bur_name,:bur_spel_code,:area_id,:hea_bur_type,:org_code,")
						.append(" :hosp_address,:hosp_phone,:staff_num,:profile,:contact_name,:contact_idnum,:contact_pos,:contact_telephone, ")
						.append(" :contact_handphone,:contact_email,:contact_qq,:status,:upd_time,:upd_user )");

				Query queryAdd = session.createSQLQuery(sqlAdd.toString());
				queryAdd.setParameter("hea_bur_id", stdHealthbureau.getHeaBurId());
				queryAdd.setParameter("hea_bur_code",
						stdHealthbureau.getHeaBurCode());
				queryAdd.setParameter("hea_bur_name",
						stdHealthbureau.getHeaBurName());
				queryAdd.setParameter("bur_spel_code",
						stdHealthbureau.getBurSpelCode());
				queryAdd.setParameter("area_id", stdHealthbureau.getArea()
						.getAreaid());
				queryAdd.setParameter("area_id", stdHealthbureau.getHeaBurType());
				queryAdd.setParameter("org_code", stdHealthbureau.getOrgCode());
				queryAdd.setParameter("hosp_address",
						stdHealthbureau.getHospAddress());
				queryAdd.setParameter("hosp_phone",
						stdHealthbureau.getHospPhone());
				queryAdd.setParameter("staff_num", stdHealthbureau.getStaffNum());
				queryAdd.setParameter("profile", stdHealthbureau.getProfile());
				queryAdd.setParameter("contact_name",
						stdHealthbureau.getContactName());
				queryAdd.setParameter("contact_idnum",
						stdHealthbureau.getContactIdnum());
				queryAdd.setParameter("contact_pos",
						stdHealthbureau.getContactPos());
				queryAdd.setParameter("contact_telephone",
						stdHealthbureau.getContactTelephone());
				queryAdd.setParameter("contact_handphone",
						stdHealthbureau.getContactHandphone());
				queryAdd.setParameter("contact_email",
						stdHealthbureau.getContactEmail());
				queryAdd.setParameter("contact_qq",
						stdHealthbureau.getContactQQ());
				queryAdd.setParameter("status", 1);
				queryAdd.setParameter("upd_time", stdHealthbureau.getUpdTime());
				queryAdd.setParameter("upd_user", stdHealthbureau.getUpdUser());
				queryAdd.executeUpdate();
			}
			writeLog(stdHealthbureau.getHeaBurId());
		}
	}

	/**
	 * @category 根据id查询卫生局信息
	 * @param id
	 * @return
	 */
	public StdHealthbureau getHeaBurInfoById(String id) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(StdHealthbureau.class);
		criteria.add(Restrictions.eq("heaBurId", id));
		return (StdHealthbureau) criteria.uniqueResult();
	}

	/**
	 * @category 记录日志
	 * @param hospInfo
	 */
	private void writeLog(String idList) {
		Session session = getSession();
		StringBuffer detail = new StringBuffer();
		StringBuffer sql11 = new StringBuffer()
				.append(" select hea_bur_code,hea_bur_name,bur_spel_code,area_id,org_code,hosp_address,hosp_phone,staff_num,profile, ")
				.append(" contact_name,contact_idnum,contact_pos,contact_telephone,contact_handphone,contact_email,contact_qq, ")
				.append(" status,upd_time,upd_user  ")
				.append(" from std_healthbureau where hea_bur_id = :heaBurId  ")
				.append(" union all   ")
				.append(" select b.*  ")
				.append(" from (select hea_bur_code,hea_bur_name,bur_spel_code,area_id,org_code,hosp_address,hosp_phone,staff_num,profile,  ")
				.append(" contact_name,contact_idnum,contact_pos,contact_telephone,contact_handphone,contact_email,contact_qq,  ")
				.append(" status,upd_time,upd_user ")
				.append(" from std_healthbureau_log  where hea_bur_id=:heaBurId order by upd_time desc limit 1)b  ");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("heaBurId", idList);
		List<?> list = dao.getSqlList(sql11.toString(), params);
		String[] Name = { "卫生局编码", "卫生局名称", "卫生局名称拼音码", "注册地行政区划代码", "组织机构代码",
				"机构地址", "机构电话", "员工数", "简介", "联系人姓名", "联系人身份证号", "联系人职务",
				"联系人电话", "联系人手机", "联系人邮箱", "联系人QQ", "状态", "更新时间", "更新人" };
		if (list.size() == 1) {
			Object[] obj = (Object[]) list.get(0);
			obj[16] = obj[16] == null ? ""
					: "1".equals(obj[14].toString()) ? "启用" : "停用";
			for (int i = 0; i < obj.length; i++) {
				detail.append(";").append(Name[i]).append(":")
						.append(obj[i] == null ? "" : obj[i].toString());
			}
			detail.delete(0, 1);
		} else {
			Object[] obj1 = (Object[]) list.get(0);// 修改后
			Object[] obj2 = (Object[]) list.get(1);// 修改前
			obj1[16] = obj1[16] == null ? ""
					: "1".equals(obj1[14].toString()) ? "启用" : "停用";
			obj2[16] = obj2[16] == null ? ""
					: "1".equals(obj2[14].toString()) ? "启用" : "停用";
			for (int i = 0; i < obj2.length; i++) {
				String a = obj1[i] == null ? "" : obj1[i].toString();
				String b = obj2[i] == null ? "" : obj2[i].toString();
				if (!(a).equals(b)) {
					detail.append(";").append(Name[i]).append(":")
							.append(obj2[i] == null ? "" : obj2[i].toString())
							.append(",")
							.append(obj1[i] == null ? "" : obj1[i].toString());
				}
			}
		}
		String uuid = UUID.randomUUID().toString();
		StringBuffer sql = new StringBuffer();
		sql.append(
				" insert into std_healthbureau_log(log_id,hea_bur_id,hea_bur_code,hea_bur_name,bur_spel_code,area_id,hea_bur_type,org_code,hosp_address,hosp_phone,staff_num,profile,")
				.append(" contact_name,contact_idnum,contact_pos,contact_telephone,contact_handphone,contact_email,contact_qq,status,upd_time,upd_user,detail) ")
				.append(" select :uuid,a.*,:detail from std_healthbureau a where a.hea_bur_id = :heaBurId ");

		Query query = session.createSQLQuery(sql.toString());
		query.setString("uuid", uuid);
		query.setString("heaBurId", idList);
		query.setString("detail", detail.toString());
		query.executeUpdate();
		session.flush();

	}
	
	public List<Map<String, Object>> getHealthBureauByOrgId(String orgId){
		Session session = sessionFactory.openSession();
		String sql = "select * from std_healthbureau where hea_bur_id = :orgId";
		Query query = session.createSQLQuery(sql);
		query.setString("orgId", orgId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<Map<String, Object>> list = query.list();
		session.clear();
		session.close();
		return list;
	}
	
	/**
	 * @category 获取管理机构中心地址信息
	 * @author 韩守松
	 * @date   2015年11月17日
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public List<StdHealthbureau> getStdHealthbureauData(){
		StringBuffer hql = new StringBuffer();
		hql.append("select hea_bur_id heaBurId,hea_bur_type heaBurType,hosp_address hospAddress from std_healthbureau where hea_bur_type = 1 ");
		SQLQuery query =  getSession().createSQLQuery(hql.toString());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}

	/**
	 * @category 根据管理机构id获取管理机构信息
	 * @author 韩守松
	 * @date   2015年11月18日
	 * @param  @param heaBurId
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public List<StdHealthbureau> queryStdHealthbureauById(String heaBurId){
		StringBuffer hql = new StringBuffer();
		hql.append(" select t.* from std_healthbureau t where t.hea_bur_id = :heaBurId ");
		Query query = getSession().createSQLQuery(hql.toString()).addEntity("t",StdHealthbureau.class);
		query.setParameter("heaBurId", heaBurId);
		return query.list();
	}
}
